import axios from 'axios'

export default {
  namespaced: true,
  state: {

    list: []

  },
  mutations: {
    unList (state, list) {
      state.list = list
    },
    setCount (state, obj) {
      const rest = state.list.find(item => item.id === obj.id)
      rest.count = obj.count
    }
  },
  actions: {
    async getList (context) {
      const res = await axios.get('http://localhost:3000/cart')
      // console.log(res)
      context.commit('unList', res.data)
    },
    async unData (context, obj) {
      await axios.patch('http://localhost:3000/cart/' + obj.id, { count: obj.count })
      context.commit('setCount', obj)
    }
  },
  getters: {
    addCount (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },
    addPrice (state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
    }
  }
}
